<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'

import { getMallVarProductList, useAddOrEditMallVar, useGetMallVarInfo } from '@fl/api/man-api'
import { SubmitBtn } from '@fl/components'
import FlUpload from '@fl/components/fl-upload.vue'
import { cloneDeep } from 'lodash-es'

import { VR_TYPE_SELECT } from './constant'

const id = defineModel<string>('id')

const { isPending, mutate } = useAddOrEditMallVar()

const { data, isLoading } = useGetMallVarInfo(id)

const visible = defineModel<boolean>('visible', { required: true })

const options = ref<any>([])

const loading = ref(false)

const dialog = computed(() => {
    return id?.value
        ? '编辑配置'
        : '新建配置'
})

const formRef = ref()

const state = ref<any>(
    {
        img: '',
        name: '',
        products: [],
        type: '',
        url: '',
    },
)

const columns: PlusColumn[] = [
    {
        colProps: {
            span: 24,
        },
        label: 'VR名称',
        prop: 'name',
        valueType: 'input',
    },
    {
        colProps: {
            span: 24,
        },
        label: '类型',
        options: VR_TYPE_SELECT,
        prop: 'type',
        valueType: 'select',
    },
    {
        colProps: {
            span: 24,
        },
        label: 'VR地址',
        prop: 'url',
        valueType: 'input',
    },
    {
        colProps: {
            span: 24,
        },
        label: '封面',
        prop: 'img',
    },
    {
        colProps: {
            span: 24,
        },
        label: '关联产品',
        prop: 'products',
    },
]

const rules = {
    img: [
        {
            message: '请上传封面',
            required: true,
        },
    ],
    name: [
        {
            message: '请输入VR名称',
            pattern: '[^ \x20]+',
            required: true,
        },
    ],
    products: [
        {
            message: '选择关联产品',
            required: true,
        },
    ],
    type: [
        {
            message: '请选择类型',
            required: true,
        },
    ],
    url: [
        {
            message: '请选择关联产品',
            required: true,
        },
    ],
}

function cancel() {
    visible.value = false
}

function reset() {
    id.value = ''
    formRef.value.formInstance.resetFields()
}

async function confirm() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const params = {
            id: id.value || '',
            img: state.value.img,
            name: state.value.name,
            products: state.value.products.map((item: any) => {
                return {
                    bizId: id.value || '',
                    bizType: 1,
                    productId: item,
                }
            }),
            status: state.value.status || 0,
            type: state.value.type,
            url: state.value.url,
        }
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                cancel()
            },
        })
    }
}

function remoteMethod(query: string) {
    if (query) {
        loading.value = true
        getMallVarProductList(query).then((res: any) => {
            options.value = res
        }).finally(() => {
            loading.value = false
        })
    }
    else {
        options.value = []
    }
}

watchEffect(() => {
    if (data.value) {
        console.log(data.value)
        state.value = cloneDeep(data.value)
        state.value.products = state.value?.productList?.map((item: any) => item.productId)
        options.value = state.value?.productList?.map((item: any) => {
            return {
                productId: item.productId,
                productName: item.productName,
            }
        })
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialog"
                width="800"
                close-on-press-escape
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    animated
        />

        <PlusForm v-else
                  ref="formRef"
                  v-model="state"
                  :columns="columns"
                  :label-width="100"
                  :rules="rules"
                  :has-footer="false"
        >
            <template #plus-field-products>
                <div class="flex flex-col gap-15 w-full items-center">
                    <el-select v-model="state.products"

                               placeholder="请输入关联产品"
                               :remote-method="remoteMethod"
                               filterable
                               remote
                               reserve-keyword
                               remote-show-suffix
                               multiple
                               :loading="loading"
                    >
                        <el-option v-for="item in options"
                                   :key="item.productId"
                                   :label="item.productName"
                                   :value="item.productId"
                        />
                    </el-select>
                </div>
            </template>

            <template #plus-field-img>
                <FlUpload :key="state.img"
                          v-model="state.img"
                          is-mall-admin
                          accept=".jpg,.png,.jpeg"
                />
            </template>
        </PlusForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="confirm"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
